# <template>
  <div class="employee-detail">
    <!-- 头部信息 -->
    <div class="header">
      <div class="header-content">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <el-avatar 
              :size="80" 
              :src="getAvatarUrl(employee.avatarHash)"
              @error="handleAvatarError"
            >
              {{ employee.realName ? employee.realName.charAt(0).toUpperCase() : 'U' }}
            </el-avatar>
            <div class="avatar-upload" v-if="isAdmin">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-icon class="avatar-icon"><Camera /></el-icon>
              </el-upload>
            </div>
          </div>
          <div class="user-info">
            <h2>{{ employee.realName }}</h2>
            <span class="group">{{ employee.groupName || '未分配车间' }}</span>
          </div>
        </div>
        <div class="actions">
          <el-button @click="$router.back()">返回</el-button>
          <el-button type="primary" @click="openEditDialog">编辑信息</el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">
              {{ employee.username }}
            </el-descriptions-item>
            <el-descriptions-item label="真实姓名">
              {{ employee.realName }}
            </el-descriptions-item>
            <el-descriptions-item label="所属车间">
              {{ employee.groupName || '未分配' }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ employee.phone || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(employee.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后更新">
              {{ formatDate(employee.updateTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ employee.remark || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 工作记录 -->
        <el-tab-pane label="工作记录" name="work">
          <work-records-view 
            v-if="activeTab === 'work'"
            :employee="employee"
            @close="activeTab = 'info'"
          />
        </el-tab-pane>

        <!-- 考勤记录 -->
        <el-tab-pane label="考勤记录" name="attendance">
          <attendance-view
            v-if="activeTab === 'attendance'"
            :employee="employee"
            @close="activeTab = 'info'"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑员工信息"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-upload-container">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              @change="handleAvatarChange"
            >
              <el-avatar 
                v-if="avatarPreview || employee.avatarHash" 
                :size="80" 
                :src="avatarPreview || getAvatarUrl(employee.avatarHash)"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-button 
              v-if="avatarPreview || employee.avatarHash"
              type="danger" 
              link 
              @click="clearAvatar"
            >
              移除头像
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>
        <el-form-item label="所属车间" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择车间">
            <el-option
              v-for="group in groups"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Camera, Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { fetchGroups } from '@/api/groups'
import { getEmployee, updateUser } from '@/api/employees'
import WorkRecordsView from './components/WorkRecordsView.vue'
import AttendanceView from './components/AttendanceView.vue'
import { uploadUserAvatar, getUserAvatarUrl } from '@/api/user'
import { useUserStore } from '@/stores/user'
import type { User, Group } from '@/types/api'

interface FormData {
  username: string
  realName: string
  groupId: string | number
  phone: string
  remark: string
}

const route = useRoute()
const router = useRouter()

// 状态
const employee = ref<User>({} as User)
const groups = ref<Group[]>([])
const activeTab = ref('info')
const showEditDialog = ref(false)
const avatarPreview = ref('')
const newAvatar = ref<File | null>(null)

// 表单相关
const formRef = ref()
const form = ref<FormData>({
  username: '',
  realName: '',
  groupId: '',
  phone: '',
  remark: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 判断是否为管理员
const userStore = useUserStore()
const isAdmin = computed(() => userStore.isAdmin)

// 获取员工信息
const fetchEmployee = async () => {
  let id = "1";
  try {
	const queryString = route.fullPath.split('?')[1]; // 提取问号后面的部分 "id=3"
	if (queryString) {
	  const params = new URLSearchParams(queryString);
	  id = params.get('id'); // 获取id的值
	} else {
	  console.log("URL中没有查询参数");
	}
    const res = await getEmployee(id)
    if (res.code === 200) {
      employee.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取员工信息失败')
  }
}

// 获取车间列表
const fetchGroupList = async () => {
  try {
    const res = await fetchGroups()
    if (res.code === 200) {
      groups.value = res.data.filter(group => 
        group.name !== '未分配组' && group.name !== '管理员组'
      )
    }
  } catch (error) {
    ElMessage.error('获取车间列表失败')
  }
}

// 打开编辑对话框
const openEditDialog = () => {
  form.value = {
    username: employee.value.username,
    realName: employee.value.realName,
    groupId: String(employee.value.groupId),
    phone: employee.value.phone,
    remark: employee.value.remark
  }
  showEditDialog.value = true
}

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 处理头像变更
const handleAvatarChange = (file: { raw: File }) => {
  newAvatar.value = file.raw
  avatarPreview.value = URL.createObjectURL(file.raw)
}

// 清除头像
const clearAvatar = () => {
  newAvatar.value = null
  avatarPreview.value = ''
  if (employee.value) {
    employee.value.avatarHash = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 先更新基本信息
    const updateData = {
      ...form.value,
      groupId: Number(form.value.groupId)
    }
    
    const res = await updateUser(employee.value.id, updateData)
    if (res.code === 200) {
      // 如果有新头像，上传头像
      if (newAvatar.value) {
        const avatarRes = await uploadUserAvatar(employee.value.id, newAvatar.value)
        if (avatarRes.code !== 200) {
          ElMessage.warning('基本信息更新成功，但头像上传失败')
        }
      }

      ElMessage.success('更新成功')
      showEditDialog.value = false
      avatarPreview.value = ''
      newAvatar.value = null
      fetchEmployee()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新失败')
    }
  }
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 处理头像上传
const handleAvatarUpload = async ({ file }: { file: File }) => {
  try {
    const res = await uploadUserAvatar(employee.value.id, file)
    if (res.code === 200) {
      ElMessage.success('头像上传成功')
      // 更新员工信息以获取新的头像hash
      await fetchEmployee()
    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error(error.message || '头像上传失败')
  }
}

// 获取头像URL
const getAvatarUrl = (hash: string) => {
  return getUserAvatarUrl(hash)
}

// 头像加载失败处理
const handleAvatarError = () => {
  // 使用默认头像或显示首字母
}

onMounted(() => {
  fetchEmployee()
  fetchGroupList()
})
</script>

<style scoped>
.employee-detail {
  min-height: 100%;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-upload:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.avatar-icon {
  color: white;
  font-size: 16px;
}

.user-info h2 {
  margin: 0 0 8px;
  font-size: 24px;
}

.group {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 16px;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px 24px;
}

:deep(.el-tabs__content) {
  background-color: #fff;
  padding: 24px;
  border-radius: 4px;
}

:deep(.avatar-uploader) {
  width: 100%;
  height: 100%;
}

:deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

:deep(.el-upload) {
  cursor: pointer;
}
</style> 